package com.example.thesunofvn.smspro;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;

public class BOSMS {
	public static List<Smss> getAllSms(Activity mActivity) {
		List<Smss> lstSms = new ArrayList<Smss>();
		Message message = null;
		Smss objSmss = null;
		Uri uri = Uri.parse("content://sms/");
		ContentResolver cr = mActivity.getContentResolver();
		String WHERE_CONDITION = null;
		String SORT_ORDER = "date DESC";
		Cursor c = cr.query(uri, new String[] { "_id", "thread_id", "address",
				"body", "read", "date", "type" }, null, null, SORT_ORDER);
		int totalSMS = c.getCount();
		if (totalSMS > 0)
			if (c.moveToFirst()) {
				while(!c.isAfterLast()) {
					objSmss = new Smss();
					message = new Message();
					message.setId(c.getString(c.getColumnIndexOrThrow("_id")));
					try {
						objSmss.setThreadId(Integer.parseInt(c.getString(c
								.getColumnIndexOrThrow("thread_id"))));
					} catch (Exception ex) {
					}
					objSmss.setAddress(c.getString(c
							.getColumnIndexOrThrow("address")));
					if (lstSms.contains(objSmss)) {
						objSmss = lstSms.get(lstSms.indexOf(objSmss));
						message.setMsg(c.getString(c.getColumnIndex("body")));

						objSmss.setReadState(c.getString(c.getColumnIndex("read")));
						message.setTime(c.getString(c.getColumnIndex("date")));
						if (c.getString(c.getColumnIndex("type")).contains("1")) {
							message.setFolderName("inbox");
						} else {
							message.setFolderName("sent");
						}
						objSmss.setSmss(message);
						c.moveToNext();
						continue;
					}
					message.setMsg(c.getString(c.getColumnIndex("body")));

					objSmss.setReadState(c.getString(c.getColumnIndex("read")));
					message.setTime(c.getString(c.getColumnIndex("date")));
					if (c.getString(c.getColumnIndex("type")).contains("1")) {
						message.setFolderName("inbox");
					} else {
						message.setFolderName("sent");
					}
					objSmss.setSmss(message);
					lstSms.add(objSmss);
					c.moveToNext();
				}
			}
		// else {
		// throw new RuntimeException("You have no SMS");
		// }
		c.close();

		return lstSms;
	}
}
